package com.nsoft.html5npub.business;

import com.nsoft.html5npub.objects.BookItem;
import com.nsoft.html5npub.utils.Constant;
import com.nsoft.html5npub.utils.utils;
import com.nsoft.html5npub.utils.viewengine;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ViewFlipper;

/**
 * load the book dynamically from different thread
 * 
 * @author minhld
 *
 */
public class BookLoader extends 
			AsyncTask<Void,Integer,Void> {
	
	private static final int LOAD_REMOVE_OLDCONTENT=0;
	private static final int LOAD_ADD_WEBVIEW=1;
	private static final int LOAD_READ_PREVIEW_FILE=2;
	private static final int LOAD_DONE=100;
	
	private Context context;
	private ViewFlipper flipper;
	private BookItem book;
	private ProgressDialog progressor=null;
	
	public BookLoader(Context ctx,
			ViewFlipper _flipper, BookItem _book){
		this.context=ctx;
		this.flipper=_flipper;
		this.book=_book;
		this.progressor=new ProgressDialog(ctx);
	}
	
	@Override
	protected void onPreExecute() {
		progressor.setCancelable(false);
		progressor.setMessage(Constant.booklist.
				BLF_BOOK_LOADING);
		progressor.show();
	}
	
	@Override
	protected Void doInBackground(Void... arg0) {
		/**
		 * read the book configuration file and load
		 * all resources to the web view
		 */
		String bookPath=utils.getBookPath()+
						Constant.PATH_SPLITTER+
	    			/* book.getContentId()+
	    			 * Constant.PATH_SPLITTER+
	    			 */
						book.getContentName();
		viewengine.setCurrentBook(this.book);
		
    	String bookConfigPath=bookPath+
				Constant.PATH_SPLITTER+
    			Constant.xml.XML_BOOK_CONFIG_FILE;
    	
    	publishProgress(LOAD_REMOVE_OLDCONTENT);
    	viewengine.getBookFromBookConfig(bookConfigPath);
    	
    	/**
    	 * load the book mark list
    	 * XML file
    	 */
    	viewengine.getBookmarkList();
    	
    	/**
    	 * start adding pages to webviews and attach to the
    	 * view flipper
    	 */
    	publishProgress(LOAD_ADD_WEBVIEW);
    	
    	/*
    	publishProgress(LOAD_READ_PREVIEW_FILE);
    	String previewPath=bookPath+
    			Constant.PATH_SPLITTER+
    			Constant.xml.XML_BOOK_PREVIEW_FILE;
    	*/
    	
    	publishProgress(LOAD_DONE);
    	
		return null;
	}
	
	@Override
	protected void onProgressUpdate(Integer... values) {
		if (values[0]==LOAD_REMOVE_OLDCONTENT){
			this.flipper.removeAllViews();
			return;
		}else if (values[0]==LOAD_ADD_WEBVIEW){
			View[] viewList=viewengine.createViews(
				this.context,(ViewGroup)this.flipper);
	    	
			for (int i=0;i<viewList.length;i++){
	    		this.flipper.addView(viewList[i]);
	    	}
			return;
		}else if (values[0]==LOAD_READ_PREVIEW_FILE){
			return;
		}else if (values[0]==LOAD_DONE){
			
		}
		progressor.dismiss();
	}
}
